package com.njworkorder.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njworkorder.DTO.DictionaryDTO;
import com.njworkorder.Entity.*;
import com.njworkorder.Service.DictionaryService;
import com.njworkorder.Utils.Result;
import com.njworkorder.Utils.ResultUtil;
import com.njworkorder.VO.DictionarySelectVo;
import com.njworkorder.VO.DictionaryVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Tag(name = "系统字典相关接口", description = "系统字典相关接口")
@RestController
@RequestMapping("/Dic")
public class DictionaryController {

    private final DictionaryService dictionaryService;
    public DictionaryController(DictionaryService dictionaryService) {
        this.dictionaryService = dictionaryService;
    }

    @Operation(summary = "根据ParentId获取系统字典配置列表")
    @GetMapping("/getParentIdList")
    public Result<Page<DictionaryVO>> getDicListTree(@RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize,
                                                     @RequestParam(value = "type", required = false) String type, @RequestParam(value = "ParentId", required = false) String ParentId) {

        MPJLambdaWrapper<Dictionary> wrapper = new MPJLambdaWrapper<Dictionary>()
                .selectAll(Dictionary.class)
                .leftJoin(DictionaryType.class, DictionaryType::getType, Dictionary::getType, ext ->
                        ext.selectAs(DictionaryType::getContent, DictionaryVO::getTypeName))
                .apply("1=1")
                .eq(type != null && !type.isEmpty(), Dictionary::getType, type)
                //.eq(ParentId ==null || ParentId.isEmpty(),Dictionary::getParentId,"")
                .eq(ParentId != null && !ParentId.isEmpty(), Dictionary::getParentId, ParentId);

        Page<DictionaryVO> dictionaryVOPage = dictionaryService.selectJoinListPage(new Page<>(pageIndex, pageSize), DictionaryVO.class, wrapper);
        return ResultUtil.success(dictionaryVOPage);
    }


    @Operation(summary = "获取系统字典配置列表")
    @GetMapping("/getDicList")
    public Result<Page<Dictionary>> getCIList(@RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize, @RequestParam("type") String type) {
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.apply("1=1")
                .eq(!type.isEmpty(), Dictionary::getType, type);


        Page<Dictionary> page = new Page<>(pageIndex, pageSize);
        Page<Dictionary> page1 = dictionaryService.page(page, queryWrapper);


        return ResultUtil.success(page1);
    }

    @Operation(summary = "根据id删除系统字典配置")
    @GetMapping("/deleteDIId")
    public Result<String> deleteDicId(@RequestParam("id") String id) {
        boolean removeById = dictionaryService.removeById(id);
        if (removeById) {
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.error("删除失败");
    }

    @Operation(summary = "根据id修改系统字典配置")
    @PostMapping("/updateAnId/{id}")
    public Result<String> updateManId(@RequestBody DictionaryDTO dictionaryDTO,
                                      @PathVariable("id") String id) {
        Dictionary Dic = new Dictionary();
        Dic.setId(id);

        BeanUtils.copyProperties(dictionaryDTO, Dic);

        boolean b = dictionaryService.updateById(Dic);
        if (b) {
            return ResultUtil.success("修改成功");
        }
        return ResultUtil.fail("修改失败");
    }

    @Operation(summary = "新增系统字典列表")
    @PostMapping("/AnInfo")
    public Result<String> addInfo(@RequestBody DictionaryDTO dictionaryDTO,
                                  @RequestHeader("Create-Ap-Id") String createApId) {
        LambdaQueryWrapper<Dictionary> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dictionary::getValusas, dictionaryDTO.getValusas());
        long count = dictionaryService.count(lambdaQueryWrapper);
        if (count > 0) {
            return ResultUtil.fail("名称已存在!");
        }
        Dictionary dic = new Dictionary();
        BeanUtils.copyProperties(dictionaryDTO, dic);
        String id = UUID.randomUUID().toString();
        dic.setId(id);
        dic.setCreateApId(createApId);

        boolean save = dictionaryService.save(dic);
        if (save) {
            return ResultUtil.success("添加成功");
        }
        return ResultUtil.fail("添加失败");
    }


    @Operation(summary = "清单配置树形结构")
    @GetMapping("/getContents")
    public Result<List<DictionaryVO>> getContents() {

        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Dictionary::getId, Dictionary::getKeysaas, Dictionary::getValusas, Dictionary::getType, Dictionary::getSortField, Dictionary::getParentId, Dictionary::getNotes);
        queryWrapper.apply("1=1");
        List<Dictionary> list = dictionaryService.list(queryWrapper);

        List<Dictionary> listF = list.stream().filter(item -> item.getParentId().isEmpty() || item.getParentId().isBlank()).toList();
        List<DictionaryVO> listLevelVo = new ArrayList<>();
        DictionaryVO dictionaryVO;
        for (Dictionary item : listF) {
            dictionaryVO = new DictionaryVO();
            BeanUtils.copyProperties(item, dictionaryVO);
            dictionaryVO.setGrade(1);
            dictionaryVO.setChildren(getAllDILevel(item.getId(), list, 2));
            listLevelVo.add(dictionaryVO);
        }
        return ResultUtil.success(listLevelVo);
    }

    public List<DictionaryVO> getAllDILevel(String id, List<Dictionary> list, int grade) {
        List<Dictionary> list1 = list.stream().filter(item -> item.getParentId().equals(id)).toList();
        List<DictionaryVO> listLevelVo = new ArrayList<>();
        DictionaryVO dictionaryVO;
        for (Dictionary item : list1) {
            dictionaryVO = new DictionaryVO();
            BeanUtils.copyProperties(item, dictionaryVO);
            dictionaryVO.setGrade(grade);
            dictionaryVO.setChildren(getAllDILevel(item.getId(), list, grade + 1));
            listLevelVo.add(dictionaryVO);
        }
        return listLevelVo;
    }


    @Operation(summary = "根据路线或字典类型等获取字典数据")
    @GetMapping("/getDictionary")
    public Result<List<DictionarySelectVo>> getDictionary(@Schema(description = "路线id") @RequestParam(value = "routeId",required = false) String routeId,
                                                          @Schema(description = "字典类型") @RequestParam(value = "type",required = false) String type,
                                                          @Schema(description = "字典id") @RequestParam(value = "id",required = false) String id) {
        List<DictionarySelectVo> list = dictionaryService.getDictionaryList(routeId, type, id);
        return ResultUtil.success(list);
    }



}
